package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.IUserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 发送手机短信验证码登录
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号码
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的四位数的短信验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4).toString();
            log.info("短信验证码为{}",code);
            //调用阿里云提供的短信服务API完成发送短信
            SMSUtils.sendMessage(
                    "阿里云短信测试",
                    "SMS_154950909",
                    phone,
                    code
            );
            //需要将生成的验证码保存到session中
            session.setAttribute(phone,code);
            return  R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 登录验证
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
   public R<User>  login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码，
        Object codeInSession = session.getAttribute(phone);

        //将页面上提交的验证码与session中的验证码进行比较,
        if (codeInSession!=null&&codeInSession.equals(code)){
            //如果相等就登陆成功
            //创建条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            //判断当前用户是否是新用户，如果是新用户就完成注册
            if (user==null){
               user  = new User();
               user.setPhone(phone);
               user.setStatus(1);
               userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);

        }
        return R.error("登陆失败");
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session){
        session.removeAttribute("employee");
        return R.success("退出成功");
    }

}
